package com.itheima.controller;
import static com.itheima.utils.RSAUtils.*;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import com.itheima.utils.RSAUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.Map;


/**
 * 会员登录
 */
@RestController
@RequestMapping("/member")
public class MemberController {

    @Reference
    private MemberService memberService;

    @Autowired
    private JedisPool jedisPool;

    //使用手机号和验证码登录
    @RequestMapping("/login")
    public Result login(HttpServletResponse response, @RequestBody Map map,HttpServletRequest request){

        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");
        //从Redis中获取缓存的验证码
        String codeInRedis = jedisPool.getResource().get(telephone+ RedisMessageConstant.SENDTYPE_LOGIN);

        if(codeInRedis == null || !codeInRedis.equals(validateCode)){
            //验证码输入错误
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }else{

            //验证码输入正确
            //判断当前用户是否为会员
            Member member = memberService.findByTelephone(telephone);
            if(member == null){
                //当前用户不是会员，自动完成注册
                member = new Member();
                member.setPhoneNumber(telephone);
                member.setRegTime(new Date());
                memberService.add(member);
                //将id放到session中
                Integer id = member.getId();
                HttpSession session = request.getSession();
                session.setAttribute("id",id);
            }
            //将id放到session中
            Integer id = member.getId();
            HttpSession session = request.getSession();
            session.setAttribute("id",id);

            //登录成功
            //写入Cookie，跟踪用户
            String encrypt = "";
            try {
                //生成公钥和私钥
                RSAUtils.genKeyPair();
                //duiCookie加密
                encrypt = encrypt(telephone, keyMap.get(0));
                System.out.println("加密后的cookie:"+encrypt);
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            Cookie cookie = new Cookie("login_member_telephone",encrypt);
            cookie.setPath("/");//路径
            cookie.setMaxAge(60 * 60 * 24 * 30);//有效期30天
            response.addCookie(cookie);

            request.setAttribute("telephone",member.getPhoneNumber());

            //保存会员信息到Redis中
            String json = JSON.toJSON(member).toString();
            jedisPool.getResource().setex(telephone, 60*30, json);
            return new Result(true, MessageConstant.LOGIN_SUCCESS);
        }

    }

    /**
     * 查询个人信息
     * @param request
     * @return
     */
    @RequestMapping("/queryMyMessage")
    public Result queryMyMessage(HttpServletRequest request){
        String telephone = (String) request.getSession().getAttribute("telephone");
        //获取cookie中的值
        Cookie[] cookies = request.getCookies();
        String value = "";
        for (Cookie cookie : cookies) {
            if("login_member_telephone".equals(cookie.getName())){
                String mun = cookie.getValue();
                //对cookie解密
                try {
                    value = decrypt(mun, keyMap.get(1));
                    System.out.println("解密后的："+value);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        //获取rides中的登录标志
        String jNumber = jedisPool.getResource().get(value);


        if(jNumber != null || jNumber.length() > 0){
            //查询个人信息
            Member data = memberService.getMyMessage(telephone);
            return new Result(true,MessageConstant.GET_MYMESSAGE_SUCCESS,data);
        }else {
            return new Result(false,MessageConstant.GET_MYMESSAGE_FAIL);
        }
    }

    /**
     * 编辑个人信息
     * @param member
     * @return
     */
    @RequestMapping("/edit")
    public Result updateById(@RequestBody Member member){
        try {
            memberService.updateById(member);
            return new Result(true,MessageConstant.UPDATE_MYMESSAGE_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.UPDATE_MYMESSAGE_FAIL);
        }
    }

    /**
     * 修改密码
     */
    @RequestMapping("/updatePassword")
    public Result updatePassword(@RequestBody Map map,HttpServletRequest request){
        if (map.get("oldPassword") == null ||
                map.get("newPassword") == null ||
                map.get("quePassword") == null
        ) {
            return new Result(false,MessageConstant.PASSWORD_NOTNULL);
        }
        Boolean flag = null;
        try {
            HttpSession session = request.getSession();
            Integer ids = (Integer) session.getAttribute("id");
            String id = String.valueOf(ids);
            flag = memberService.updatePassword(map,id);
            return new Result(flag,MessageConstant.UPDATE_PASSWORD_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(flag,MessageConstant.UPDATE_PASSWORD_FAIL);
        }
    }

    /**
     * 密码登录
     * @param map
     * @return
     */
    @RequestMapping("/PWLogin")
    public Result PWLogin(@RequestBody Map map,HttpServletResponse response,HttpServletRequest request){
        String telephone = (String) map.get("telephone");
        //验证码输入正确
        //判断当前用户是否为会员
        Member member = memberService.findByTelephone(telephone);
        if(member == null){
            //当前用户不是会员，自动完成注册
            member = new Member();
            member.setPhoneNumber(telephone);
            member.setRegTime(new Date());
            memberService.add(member);
            //将id放到session中
            Integer id = member.getId();
            HttpSession session = request.getSession();
            session.setAttribute("id",id);
        }
        //将id放到session中
        Integer id = member.getId();
        HttpSession session = request.getSession();
        session.setAttribute("id",id);

        //登录成功
        //写入Cookie，跟踪用户
        String encrypt = "";
        try {
            //生成公钥和私钥
            RSAUtils.genKeyPair();
            //duiCookie加密
            encrypt = encrypt(telephone, keyMap.get(0));
            System.out.println("加密后的cookie:"+encrypt);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Cookie cookie = new Cookie("login_member_telephone",encrypt);
        cookie.setPath("/");//路径
        cookie.setMaxAge(60 * 60 * 24 * 30);//有效期30天
        response.addCookie(cookie);

        //保存会员信息到Redis中
        String json = JSON.toJSON(member).toString();
        jedisPool.getResource().setex(telephone, 60*30, json);
        //把手机号封装到session中
        request.getSession().setAttribute("telephone",map.get("telephone"));
        return new Result(true, MessageConstant.LOGIN_SUCCESS);


       /* Boolean flag;
            flag = memberService.PWLogin(map);
            if (!flag) {
                return new Result(flag,MessageConstant.PHONE_OR_PASSWORD_ERROR);
            }*/
            //把手机号封装到session中
        /*request.getSession().setAttribute("telephone",map.get("telephone"));
        return new Result(flag,MessageConstant.LOGIN_SUCCESS);*/
    }

    /**
     * 修改手机号
     */
    @RequestMapping("/updatePhoneNumber")
    public Result updatePhoneNumber(@RequestBody Map map,HttpServletRequest request){
        //判断验证码输入是否正确
        String telephone = (String) map.get("telephone");
        //判断当前输入手机号是否是登录手机号
        String redisTelephone = (String) request.getSession().getAttribute("telephone");
        if (!telephone.equals(redisTelephone)) {
            return new Result(false,MessageConstant.CURRENT_TELEPHONE_UNLIKE);
        }
        String code = jedisPool.getResource().get(telephone + "Update");
        if (code == null || code.length() == 0) {
            return new Result(false,MessageConstant.SEND_VALIDATECODE_FAIL);
        }
        //判断两次手机号输入是否一致
        String newTelephone = (String) map.get("newTelephone");
        String queTelephone = (String) map.get("queTelephone");
        if (newTelephone == null || queTelephone == null || !newTelephone.equals(queTelephone)) {
            return new Result(false,MessageConstant.TO_TELEPHONE_UNLIKE);
        }
        try {
            memberService.updatePhoneNumber(map);
            return new Result(true,MessageConstant.UPDATE_PHONENUMBER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.UPDATE_PHONENUMBER_FAIL);
        }
    }
}